package com.yzg.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author misterWei
 * @create 2020年05月13号:22点06分
 * @mailbox forcontinue@163.com
 * 锁超时
 */
@Slf4j(topic = "c.lockTimeOut")
public class LockTimeOut {
    private static final ReentrantLock lock = new ReentrantLock();

/*    public static void main(String[] args) {
        Thread t1 = new Thread(() ->{

            log.debug("尝试获取锁.");
            if (!lock.tryLock()) {
                log.debug("没有获取到锁.");
                return;
            }

            lock.lock();
            try {
                log.debug("获取到锁了.");
            }finally {
                lock.unlock();
            }

        }, "t1");
        lock.lock();
        t1.start();
    }*/

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() ->{

            log.debug("尝试获取锁.");
            try {
                if (!lock.tryLock(2L, TimeUnit.SECONDS)) {
                    log.debug("没有获取到锁.");
                    return;
                }
            } catch (InterruptedException e) {
                log.error("被打断了");
            }

            lock.lock();
            try {
                log.debug("获取到锁了.");
            }finally {
                lock.unlock();
            }

        }, "t1");
        lock.lock();
        t1.start();
        Thread.sleep(1000L);
        lock.unlock();
    }
}
